package com.admin.weixinpay;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ：wbt
 * @date ：Created in 2019/7/17 0017 14:13
 * @description：返回数据处理
 * @version: 1$
 */
public class PayUtil {
    /**
     * 读取输入流字符串
     * @param is
     * @return
     */
    public static String StreamRead(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[512];
            while((len = is.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            return new String(baos.toByteArray(), 0, baos.size(), "utf-8");
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    }
    public static Map<String,String> XmlTOMap(String xml){
        //匹配一段一段这样的数据   <attach><![CDATA[支付测试]]></attach>
        Pattern pattern = Pattern.compile("<.*?/.*?>");
        Matcher matcher = pattern.matcher(xml);
        //配置是否包含<![CDATA[CNY]]> CDATA 包裹的数据
        Pattern pattern2 = Pattern.compile("!.*]");
        Map<String, String> map = new HashMap<>();
        while(matcher.find()) {
            //获取键
            String key = matcher.group().replaceAll(".*/", "");
            key = key.substring(0, key.length() - 1);
            Matcher matcher2 = pattern2.matcher(matcher.group());
            String value = matcher.group().replaceAll("</?.*?>", "");
            //获取值
            if(matcher2.find() && !value.equals("DATA")) {
                value = matcher2.group().replaceAll("!.*\\[", "");
                value = value.substring(0, value.length() - 2);
            }
            map.put(key, value);
        }
        return map;
    }

}
